<?php
namespace App\Admin\Controllers\Stocking;

use App\Admin\Actions\Stocking\ImportJpSku;
use App\Admin\Extensions\Grid\Tool\Export;
use App\Models\Basics\SysPlat;
use App\Models\Inventory\PublicCn;
use App\Models\Product\ProductClassify;
use App\Models\SalesReport\DailyVolume;
use App\Models\SsBasic\JpSku;
use App\Models\SsBasic\JpSkuEstimate;
use App\Models\SsBasic\JpStockingSku;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Request;
class JpSkuController extends AdminController{

    protected $title = 'JP(平台)备货产品';

    protected function grid()
    {
        $grid = new Grid(new JpStockingSku());
        $grid->model()->where('enable_status',1)->collection(function (Collection $collection){
            foreach($collection as $item) {
                $item->cnp_instant_num = PublicCn::getInstant($item->psku_id);
                $tj = JpStockingSku::getSystemTJ($item);
                $item->system_tj = $tj['num'];
                $item->system_tj_desc = $tj['desc'];
                $item->system_tj_free = $tj['free'];

                $item->estimate_total = 0;
                for($i = 0; $i < JpSkuEstimate::ESTIMATE_NUM; $i++){
                    $item->estimate_total += $item->{'estimate_num'.$i};
                }
            }
            return $collection;
        });
        $grid->column('sku.psku_cn','产品名称')->totalRow('当期汇总：');
        $grid->column('plat.title','平台');
        $grid->column('sku.psku_code','SKU');
        $grid->column('skuClassify.season','季节性')->using(ProductClassify::$_season);
        $grid->column('area_sku.type','来源')->display(function ($value){
            return $value ? JpSku::$_type[$value] : '';
        });
        $grid->column('ratio.ratio','销售比例')->display(function ($value){
            return ($value && $value > 0) ? $value * 100 . '%' : "<span style='color: red'>null</span>";
        });
        $grid->column('recommend_ratio7','推荐备货比例(7天)')->display(function ($value){
            return ($value && $value > 0) ? $value * 100 . '%' : "<span style='color: red'>0</span>";
        });
        $grid->column('recommend_ratio30','推荐备货比例(30天)')->display(function ($value){
            return ($value && $value > 0) ? $value * 100 . '%' : "<span style='color: red'>0</span>";
        });
        $grid->column('skuClassify.title','品类');
        $grid->column('avg3','3天AVG')->totalRow();
        $grid->column('avg7','7天AVG')->totalRow();
        $grid->column('avg15','15天AVG')->totalRow();
        $grid->column('avg30','30天AVG')->totalRow();
        $grid->column('avg','AVG')->totalRow();
        $grid->column('fba_instant_num','FBA在库')->totalRow()->sortable();
        $grid->column('fba_transit_num','FBA在途')->totalRow()->sortable();
        $grid->column('cnp_instant_num','公共在库');
        $grid->column('cn_instant_num','国内在库')->sortable()->totalRow();
        $grid->column('cn_transit_num','国内在途')->sortable()->totalRow();
        $grid->column('os_instant_num','海外仓在库')->sortable()->totalRow();
        $grid->column('os_transit_num','海外仓在途')->sortable()->totalRow();
        $grid->column('purchase_cycle','生产周期');
        $grid->column('air_day','空运时效');
        $grid->column('air_available','空运最快可售')->display(function ($value){
            return JpStockingSku::getSaleDate($value);
        });
        $grid->column('sea_day','海运时效');
        $grid->column('sea_available','海运最快可售')->display(function ($value){
            return JpStockingSku::getSaleDate($value);
        });
        $grid->column('air_ship_factor','空运发货库存系数')->view('stocking.sku.ship-factor')->help('安全系数和目前系数，总数：FBA库存(+海外仓库存)');
        $grid->column('sea_ship_factor','海运发货库存系数')->view('stocking.sku.ship-factor')->help('安全系数和目前系数，总数：FBA库存(+海外仓库存)');
        $grid->column('air_stock_factor','空运备货库存系数')->view('stocking.sku.stock-factor')->help('安全系数和目前系数，总数：所有库存(不含公共库存)');
        $grid->column('sea_stock_factor','海运备货库存系数')->view('stocking.sku.stock-factor')->help('安全系数和目前系数，总数：所有库存(不含公共库存)');
        $grid->column('estimate_total','预估量');

        for($i = 0; $i < JpSkuEstimate::ESTIMATE_NUM; $i++){
            $grid->column('estimate_num'.$i,date('y/m',strtotime("midnight first day of $i month")).'预估')
                ->totalRow()
                ->display(function ($value) use ($i){
                    $thisIndex = JpStockingSku::setMonthOr2Month($this->set_date,$this->sea_available);
                    if($thisIndex == $i){
                        return "<span style='background-color: #00c0ef;'>$value</span>";
                    }else{
                        return $value;
                    }
                });
        }
        $grid->column('system_tj','备货推荐');
        $grid->column('system_tj_desc','推荐说明')->view('stocking.sku.tj-desc');
        $grid->column('system_tj_free','可调剂库存');
        $grid->column('over_stock','积压库存')->totalRow();
        $grid->column('over_stock_value','积压货值')->totalRow();
        //$grid->column('status','状态')->display(function ($value){
        //    return JpStockingSku::$_status[$value];
        //});

        //JP往期销量汇总(去年同期销量数据)
        $yearDate = date('Y',strtotime("-1 year", time()));
        $prevVolume = DailyVolume::getPrevVolume(Request::input(), 'JP');
        $script = <<<SCRIPT
            $(function($){
                 <!--$(".table tfoot").css({'color':'red'});-->
                 $(".table tfoot:first" ).append(`<tr>
                    <!--<td class="column-__row_selector__" style="background: #ffffff;position: sticky;left: 0;"></td>-->
                    <td class="column-sku-psku_cn" colspan="4" style="background: white;position: sticky;line-height: 15px;left: 0px;"></br>往期销量汇总：({$yearDate})</td>
                    <!--<td class="column-area-area"></td>-->
                    <!--<td class="column-sku-psku_code"></td>-->
                    <!--<td class="column-sku_classify-season"></td>-->
                    <td class="column-area_sku-type"></td>
                    <td class="column-ratio-ratio"></td>
                    <td class="recommend_ratio7"></td>
                    <td class="recommend_ratio30"></td>
                    <td class="column-sku_classify-title"></td>
                    <td class="column-avg3"></td>
                    <td class="column-avg7"></td>
                    <td class="column-avg15"></td>
                    <td class="column-avg30"></td>
                    <td class="column-avg"></td>
                    <td class="column-fba_instant_num"></td>
                    <td class="column-fba_transit_num"></td>
                    <td class="column-cnp_instant_num"></td>
                    <td class="column-cn_instant_num"></td>
                    <td class="column-cn_transit_num"></td>
                    <td class="column-os_instant_num"></td>
                    <td class="column-os_transit_num"></td>
                    <td class="column-purchase_cycle"></td>
                    <td class="column-air_day"></td>
                    <td class="column-air_available"></td>
                    <td class="column-sea_day"></td>
                    <td class="column-sea_available"></td>
                    <td class="column-air_ship_factor"></td>
                    <td class="column-sea_ship_factor"></td>
                    <td class="column-air_stock_factor"></td>
                    <td class="column-sea_stock_factor"></td>
                    <td class="column-estimate_total"></td>
                    <td class="column-estimate_num0"><b>{$prevVolume['month0']}</b><br> {$prevVolume['estimate_num0']}</td>
                    <td class="column-estimate_num1"><b>{$prevVolume['month1']}</b><br> {$prevVolume['estimate_num1']}</td>
                    <td class="column-estimate_num2"><b>{$prevVolume['month2']}</b><br> {$prevVolume['estimate_num2']}</td>
                    <td class="column-estimate_num3"><b>{$prevVolume['month3']}</b><br> {$prevVolume['estimate_num3']}</td>
                    <td class="column-estimate_num4"><b>{$prevVolume['month4']}</b><br> {$prevVolume['estimate_num4']}</td>
                    <td class="column-estimate_num5"><b>{$prevVolume['month5']}</b><br> {$prevVolume['estimate_num5']}</td>
                    <td class="column-estimate_num6"><b>{$prevVolume['month6']}</b><br> {$prevVolume['estimate_num6']}</td>
                    <td class="column-estimate_num7"><b>{$prevVolume['month7']}</b><br> {$prevVolume['estimate_num7']}</td>
                    <td class="column-estimate_num8"><b>{$prevVolume['month8']}</b><br> {$prevVolume['estimate_num8']}</td>
                    <td class="column-estimate_num9"><b>{$prevVolume['month9']}</b><br> {$prevVolume['estimate_num9']}</td>
                    <td class="column-estimate_num10"><b>{$prevVolume['month10']}</b><br> {$prevVolume['estimate_num10']}</td>
                    <td class="column-estimate_num11"><b>{$prevVolume['month11']}</b><br> {$prevVolume['estimate_num11']}</td>
                    <td class="column-estimate_num12"><b>{$prevVolume['month12']}</b><br> {$prevVolume['estimate_num12']}</td>
                    <td class="column-estimate_num13"><b>{$prevVolume['month13']}</b><br> {$prevVolume['estimate_num13']}</td>
                    <td class="column-estimate_num14"><b>{$prevVolume['month14']}</b><br> {$prevVolume['estimate_num14']}</td>
                    <td class="column-estimate_num15"><b>{$prevVolume['month15']}</b><br> {$prevVolume['estimate_num15']}</td>
                    <td class="column-estimate_num16"><b>{$prevVolume['month16']}</b><br> {$prevVolume['estimate_num16']}</td>
                    <td class="column-estimate_num17"><b>{$prevVolume['month17']}</b><br> {$prevVolume['estimate_num17']}</td>
                    <td class="column-system_tj"></td>
                    <td class="column-system_tj_desc"></td>
                    <td class="column-system_tj_free"></td>
                    <td class="column-over_stock"></td>
                    <td class="column-over_stock_value"></td>
                    <td class="column-apply_num"></td>
                    <td class="column-apply_remark"></td>
                    <td class="column-approval_num"></td>
                    <td class="column-approval_remark"></td>
                    <td class="column-status" style="right: 0; box-shadow: -5px 0 5px -5px rgba(0,0,0,.12);width: 58px;height: 37px;position: sticky;background: #FFFFFF;"></td>
                 </tr>`);
            });
SCRIPT;
        \Encore\Admin\Admin::script($script);

        //JP往期销量汇总(前年同期销量数据)
        $yearDate2 = date('Y',strtotime("-2 year", time()));
        $prevVolume2 = DailyVolume::getPrevVolume(Request::input(), 'JP', 2);
        $script = <<<SCRIPT
            $(function($){
                 <!--$(".table tfoot").css({'color':'red'});-->
                 $(".table tfoot:first").append(`<tr>
                    <!--<td class="column-__row_selector__" style="background: #ffffff;position: sticky;left: 0;"></td>-->
                    <td class="column-sku-psku_cn" colspan="4" style="background: white;position: sticky;line-height: 15px;left: 0px;"></br>往期销量汇总：({$yearDate2})</td>
                    <!--<td class="column-area-area"></td>-->
                    <!--<td class="column-sku-psku_code"></td>-->
                    <!--<td class="column-sku_classify-season"></td>-->
                    <td class="column-area_sku-type"></td>
                    <td class="column-ratio-ratio"></td>
                    <td class="recommend_ratio7"></td>
                    <td class="recommend_ratio30"></td>
                    <td class="column-sku_classify-title"></td>
                    <td class="column-avg3"></td>
                    <td class="column-avg7"></td>
                    <td class="column-avg15"></td>
                    <td class="column-avg30"></td>
                    <td class="column-avg"></td>
                    <td class="column-fba_instant_num"></td>
                    <td class="column-fba_transit_num"></td>
                    <td class="column-cnp_instant_num"></td>
                    <td class="column-cn_instant_num"></td>
                    <td class="column-cn_transit_num"></td>
                    <td class="column-os_instant_num"></td>
                    <td class="column-os_transit_num"></td>
                    <td class="column-purchase_cycle"></td>
                    <td class="column-air_day"></td>
                    <td class="column-air_available"></td>
                    <td class="column-sea_day"></td>
                    <td class="column-sea_available"></td>
                    <td class="column-air_ship_factor"></td>
                    <td class="column-sea_ship_factor"></td>
                    <td class="column-air_stock_factor"></td>
                    <td class="column-sea_stock_factor"></td>
                    <td class="column-estimate_total"></td>
                    <td class="column-estimate_num0"><b>{$prevVolume2['month0']}</b><br> {$prevVolume2['estimate_num0']}</td>
                    <td class="column-estimate_num1"><b>{$prevVolume2['month1']}</b><br> {$prevVolume2['estimate_num1']}</td>
                    <td class="column-estimate_num2"><b>{$prevVolume2['month2']}</b><br> {$prevVolume2['estimate_num2']}</td>
                    <td class="column-estimate_num3"><b>{$prevVolume2['month3']}</b><br> {$prevVolume2['estimate_num3']}</td>
                    <td class="column-estimate_num4"><b>{$prevVolume2['month4']}</b><br> {$prevVolume2['estimate_num4']}</td>
                    <td class="column-estimate_num5"><b>{$prevVolume2['month5']}</b><br> {$prevVolume2['estimate_num5']}</td>
                    <td class="column-estimate_num6"><b>{$prevVolume2['month6']}</b><br> {$prevVolume2['estimate_num6']}</td>
                    <td class="column-estimate_num7"><b>{$prevVolume2['month7']}</b><br> {$prevVolume2['estimate_num7']}</td>
                    <td class="column-estimate_num8"><b>{$prevVolume2['month8']}</b><br> {$prevVolume2['estimate_num8']}</td>
                    <td class="column-estimate_num9"><b>{$prevVolume2['month9']}</b><br> {$prevVolume2['estimate_num9']}</td>
                    <td class="column-estimate_num10"><b>{$prevVolume2['month10']}</b><br> {$prevVolume2['estimate_num10']}</td>
                    <td class="column-estimate_num11"><b>{$prevVolume2['month11']}</b><br> {$prevVolume2['estimate_num11']}</td>
                    <td class="column-estimate_num12"><b>{$prevVolume2['month12']}</b><br> {$prevVolume2['estimate_num12']}</td>
                    <td class="column-estimate_num13"><b>{$prevVolume2['month13']}</b><br> {$prevVolume2['estimate_num13']}</td>
                    <td class="column-estimate_num14"><b>{$prevVolume2['month14']}</b><br> {$prevVolume2['estimate_num14']}</td>
                    <td class="column-estimate_num15"><b>{$prevVolume2['month15']}</b><br> {$prevVolume2['estimate_num15']}</td>
                    <td class="column-estimate_num16"><b>{$prevVolume2['month16']}</b><br> {$prevVolume2['estimate_num16']}</td>
                    <td class="column-estimate_num17"><b>{$prevVolume2['month17']}</b><br> {$prevVolume2['estimate_num17']}</td>
                    <td class="column-system_tj"></td>
                    <td class="column-system_tj_desc"></td>
                    <td class="column-system_tj_free"></td>
                    <td class="column-over_stock"></td>
                    <td class="column-over_stock_value"></td>
                    <td class="column-apply_num"></td>
                    <td class="column-apply_remark"></td>
                    <td class="column-approval_num"></td>
                    <td class="column-approval_remark"></td>
                    <td class="column-status" style="right: 0; box-shadow: -5px 0 5px -5px rgba(0,0,0,.12);width: 58px;height: 37px;position: sticky;background: #FFFFFF;"></td>
                 </tr>`);
            });
SCRIPT;
        \Encore\Admin\Admin::script($script);

        if (Admin::user()->inRoles(['sales-executive','jp-sales-executive','salesperson','jp-salesperson','sales-director','administrator'])) {
            $grid->tools(function (Grid\Tools $tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete(); //禁用批量删除
                });
                $tools->append(new ImportJpSku()); //导入
                $tools->append(new Export('stocking/jp-sku-download')); //导出
            });
        }

        $grid->disableBatchActions();
        $grid->expandFilter();
        $grid->disableExport();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->fixColumns(4,0);
        $grid->paginate(10);
        $grid->filter(function($filter){
            $filter->column(1/3, function ($filter) {
                $filter->where(function ($query) {
                    $query->whereHas('sku', function ($query) {
                        $query->where('psku_code', 'like', "%{$this->input}%")
                            ->orWhere('psku_cn', 'like', "%{$this->input}%");
                    });
                }, 'SKU','sku8')->placeholder('模糊查询SKU，名称');
                $filter->equal('plat_id','平台')->select(SysPlat::$_platformNormal);
            });
            $filter->column(1/3, function ($filter){
                $filter->equal('skuClassify.season', '季节性')->select(ProductClassify::$_season);
            });
            $filter->column(1/3, function ($filter) {
                $filter->equal('sku.classify_id', '品类')->select(ProductClassify::options());
                //$filter->equal('status', '状态')->select(JpStockingSku::$_status);
                //$filter->equal('area_sku.type', '来源')->select(JpSku::$_type);
            });
        });
        return $grid;
    }

    protected function form()
    {
        $form = new Form(new JpStockingSku());
        $form->text('apply_num');
        $form->text('apply_remark');
        $form->text('cn_transit_num');

        $form->saved(function (Form $form) {
            $form->model()->over_stock = JpStockingSku::getOverStock($form->model());
            $form->model()->over_stock_value = JpStockingSku::getOverStockValue($form->model()->over_stock,$form->model()->unit_price);
            $form->model()->save();
        });
        return $form;
    }

    public function download(){
        $request = Request::input();
        $query = $this->_initQuery($request);
        $this->_exeDownload($query);
    }

    private function _initQuery($filters){
        $query = JpStockingSku::query()->orderBy('id', 'DESC');
        foreach ($filters as $key => $_filter){
            if($key == 'sku8'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('psku_code', 'like', "%{$_filter}%")
                        ->orWhere('psku_cn', 'like', "%{$_filter}%");
                });
            }
            if($key == 'sku'){
                $query->whereHas('sku', function ($query) use($_filter){
                    $query->where('classify_id', $_filter['classify_id']);
                });
            }
            if($key == 'area_sku'){
                $query->whereHas('area_sku', function ($query) use($_filter){
                    $query->where('type', $_filter['type']);
                });
            }
            if($key == 'skuClassify'){
                $query->whereHas('skuClassify', function ($query) use($_filter){
                    $query->where('season', $_filter['season']);
                });
            }
            if(in_array($key,['plat_id','status'])){
                $query->where($key,$_filter);
            }
        }
        return $query;
    }

    private function _exeDownload($query){
        JpStockingSku::exeDownload($query);
    }
}
